<template>
  <div class="app-container">
    <Header header-title="购物车"></Header>
    <Goods
      v-for="item in goodsList"
      :key="item.id"
      :id="item.id"
      v-model:state="item.goods_state"
      :image="item.goods_img"
      :title="item.goods_name"
      :price="item.goods_price"
      :count="item.goods_count"
    >
    </Goods>
    <Footer
      :is-all-checked="isAllSelected"
      :amount="amount"
      :total-count="totalCount"
      @all-selected="updateState"
    ></Footer>
  </div>
</template>

<script>
// 导入组件
import Header from '../Header.vue'
import Footer from '../Footer.vue'
import Goods from './Goods.vue'
// 导入 bus
import bus from './eventBus.js'

export default {
  name: 'MyApp',
  components: {
    Header,
    Footer,
    Goods
  },
  data() {
    return {
      goodsList: []
    }
  },
  created() {
    this.initGoodsList()
    bus.on('updateNum', val => {
      // console.log(val)
      this.goodsList.some(item => {
        if (item.id === val.id) {
          item.goods_count = val.newNum
          return true
        }
      })
    })
  },
  methods: {
    async initGoodsList() {
      const { data: res } = await this.$http.get('/api/cart')
      console.log(res)
      if (res.status === 200) {
        this.goodsList = res.list
      }
    },
    updateState(val) {
      // console.log(val)
      this.goodsList.forEach(item => (item.goods_state = val))
    }
  },
  computed: {
    // 是否全选
    isAllSelected() {
      return this.goodsList.every(item => item.goods_state)
    },
    // 勾选商品总价
    amount() {
      return this.goodsList
        .filter(item => item.goods_state)
        .reduce((amt, i) => amt + i.goods_price * i.goods_count, 0)
    },
    // 勾选商品总数
    totalCount() {
      return this.goodsList
        .filter(item => item.goods_state)
        .reduce((count, i) => count + i.goods_count, 0)
    }
  }
}
</script>

<style lang="less" scoped>
.app-container {
  padding-top: 45px;
  padding-bottom: 50px;
}
</style>
